﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Zeus.Mvc.Loggers;
using Zeus.Mvc.Loggers.Implementations;
using Microsoft.Extensions.Logging;
using System.IO;
namespace ZeusCore.Performance.Test
{
    public class ConsoleHttpContextLogger : DefaultHttpContextLogger
    {
        private StringBuilder _stringBuilder;

        private Stopwatch stopwatch;
        private ILogger _logger;
        public ConsoleHttpContextLogger(ILogger<ConsoleHttpContextLogger> logger)
        {
            _stringBuilder = new StringBuilder();
            _logger = logger;
            stopwatch = new Stopwatch();
            stopwatch.Start();
        }

        protected override async Task<IHttpContextModel> BuildRequestModel(HttpContext httpContext)
        {
            var requestModel = await base.BuildRequestModel(httpContext);
            //Console.WriteLine("************Request:");
            //Console.WriteLine(JsonConvert.SerializeObject(requestModel));
            _stringBuilder.Append($"*******request  exec {stopwatch.ElapsedTicks} ms");



            return requestModel;
        }

        protected override async Task<IHttpContextModel> BuildResponseModel(HttpContext httpContext)
        {
            var responseModel = await base.BuildResponseModel(httpContext);
            //Console.WriteLine("************Response:");
            //Console.WriteLine(JsonConvert.SerializeObject(responseModel));
            _stringBuilder.Append($"*******response  exec {stopwatch.ElapsedTicks} ms");
            return responseModel;
        }

        protected override async Task<IHttpContextModel> BuildExceptionModel(HttpContext httpContext, Exception ex)
        {
            var exceptionModel = await base.BuildExceptionModel(httpContext, ex);
            //Console.WriteLine("************Exception:");
            //Console.WriteLine(JsonConvert.SerializeObject(exceptionModel));
            return exceptionModel;
        }

        public override async Task ResponseLog(HttpContext httpContext)
        {
            await base.ResponseLog(httpContext);
            _stringBuilder.Append($"*******finish  exec {stopwatch.ElapsedTicks} ms");

            //  _logger.LogInformation(_stringBuilder.ToString());
            LogInfo(_stringBuilder.ToString());
            stopwatch.Stop();
        }

        private void LogInfo(string content)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs/2018-08-16.txt");
            using (var file = File.Open(path, FileMode.OpenOrCreate))
            {
                using (var sw = new StreamWriter(file))
                {
                    sw.WriteLine(content);
                    sw.Flush();
                }
                
            }

        }
    }
}
